import { useState, useEffect } from "react";
import { Tree, Button, Modal, Input, Space, Card, Divider } from "antd";
import { message } from "../../utils/customMessage";
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  MenuOutlined,
} from "@ant-design/icons";
import type { DataNode } from "antd/es/tree";
import { http } from "../../utils/request";
import CustomConfirmModal from "../../components/CustomConfirmModal";
import "antd/dist/reset.css";

interface MenuNode extends DataNode {
  key: string;
  title: string;
  children?: MenuNode[];
  path: string;
  component: string;
  id?: number;
  editAble?: number;
}

// 定义菜单API返回的数据类型
interface MenuApiData {
  id: number;
  parentId: number;
  menuName: string;
  url: string;
  description?: string;
  editAble: number;
  menuList?: MenuApiData[];
  component?: string;
}

const MenuManager = () => {
  const [treeData, setTreeData] = useState<MenuNode[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<"add" | "edit" | "addRoot">("add");
  const [newMenuName, setNewMenuName] = useState("");
  const [selectedNode, setSelectedNode] = useState<MenuNode | null>(null);
  const [loading, setLoading] = useState(false);

  // 添加删除确认弹窗的状态
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
  const [deleteTargetNode, setDeleteTargetNode] = useState<MenuNode | null>(
    null
  );

  // 获取菜单数据
  useEffect(() => {
    loadMenuData();
  }, []);

  // 从接口加载菜单数据
  const loadMenuData = async () => {
    setLoading(true);
    try {
      const result = await http.get("/api/menu/tree");

      if (+result.status === 200 && result.data) {
        setTreeData(convertToTreeData(result.data));
      } else {
        message.error(result.message || "获取菜单数据失败");
      }
    } catch (error) {
      console.error("获取菜单数据失败:", error);
      message.error("获取菜单数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 转换模块数据为树形结构
  const convertToTreeData = (menuList: MenuApiData[]): MenuNode[] => {
    return menuList.map((menu) => ({
      key: menu.url,
      title: menu.menuName,
      path: menu.url,
      component: menu.component || "",
      id: menu.id,
      editAble: menu.editAble,
      children: menu.menuList ? convertToTreeData(menu.menuList) : undefined,
    }));
  };

  // 重新获取数据并同步到localStorage和侧边栏
  const refreshMenuData = async () => {
    try {
      // 1. 重新调用 /api/menu/tree 获取最新数据
      const treeResult = await http.get("/api/menu/tree");

      if (+treeResult.status === 200 && treeResult.data) {
        // 2. 更新当前页面的数据
        setTreeData(convertToTreeData(treeResult.data));

        // 重新调用 userInfo 接口获取最新数据
        const userId = localStorage.getItem("userId");
        if (userId) {
          const userInfoResult = await http.get(
            `/api/user/userInfo?id=${userId}`
          );

          if (+userInfoResult.status === 200 && userInfoResult.data) {
            localStorage.setItem(
              "userInfo",
              JSON.stringify(userInfoResult.data)
            );

            // 更新角色ID（防止角色信息变更）
            localStorage.setItem(
              "roleId",
              userInfoResult.data.role.id.toString()
            );

            // 触发菜单更新事件，通知Layout组件刷新侧边菜单
            window.dispatchEvent(
              new CustomEvent("userInfoUpdated", {
                detail: userInfoResult.data,
              })
            );

            message.info("您的权限已更新，左侧菜单将自动刷新");
          }
        }
      }
    } catch (error) {
      console.error("同步菜单数据失败:", error);
      message.error("同步菜单数据失败");
    }
  };

  // 智能更新菜单列表的函数
  const updateMenuList = (
    originalMenuList: MenuApiData[],
    newMenuList: MenuApiData[]
  ): MenuApiData[] => {
    // 创建新数据的 ID 映射，方便快速查找
    const newMenuMap = createMenuMap(newMenuList);

    // 递归更新菜单项
    const updateMenuItems = (menuItems: MenuApiData[]): MenuApiData[] => {
      const updatedItems: MenuApiData[] = [];

      // 遍历新数据，确保所有新数据都被包含
      newMenuList.forEach((newItem) => {
        const updatedItem = updateSingleMenuItem(newItem, newMenuMap);
        if (updatedItem) {
          updatedItems.push(updatedItem);
        }
      });

      return updatedItems;
    };

    return updateMenuItems(originalMenuList);
  };

  // 创建菜单 ID 映射
  const createMenuMap = (menuList: MenuApiData[]): Map<number, MenuApiData> => {
    const menuMap = new Map<number, MenuApiData>();

    const addToMap = (items: MenuApiData[]) => {
      items.forEach((item) => {
        menuMap.set(item.id, item);
        if (item.menuList && item.menuList.length > 0) {
          addToMap(item.menuList);
        }
      });
    };

    addToMap(menuList);
    return menuMap;
  };

  // 更新单个菜单项
  const updateSingleMenuItem = (
    newItem: MenuApiData,
    newMenuMap: Map<number, MenuApiData>
  ): MenuApiData => {
    const updatedItem: MenuApiData = {
      id: newItem.id,
      parentId: newItem.parentId,
      menuName: newItem.menuName,
      url: newItem.url,
      description: newItem.description,
      editAble: newItem.editAble,
      component: newItem.component,
      menuList: undefined,
    };

    // 如果有子菜单，递归处理
    if (newItem.menuList && newItem.menuList.length > 0) {
      updatedItem.menuList = newItem.menuList.map((childItem) =>
        updateSingleMenuItem(childItem, newMenuMap)
      );
    }

    return updatedItem;
  };

  // 检查是否可以编辑
  const canEdit = (node: MenuNode) => {
    // editAble === 1 时不可编辑
    if (node.editAble === 1) {
      return false;
    }
    // editAble === 0 时可编辑
    return node.editAble === 0;
  };

  // 检查是否可以删除
  const canDelete = (node: MenuNode) => {
    console.log(node, "node");

    // editAble === 1 时不可删除
    if (node.editAble === 1) {
      return false;
    }
    // editAble === 0 时可删除
    return node.editAble === 0;
  };

  // 检查是否可以添加子菜单
  const canAddChild = (node: MenuNode) => {
    // 首页不允许添加子菜单
    const protectedPaths = [
      "/home",
      "/menuManager",
      "/userManager",
      "/roleManager",
      "/operationLog",
    ];
    if (protectedPaths.includes(node.path)) {
      return false;
    }

    const menuLevel = getMenuLevel(node);
    // 最多4级菜单
    if (menuLevel >= 4) {
      return false;
    }

    // editAble === 0 或 === 1 时都可以添加子菜单（除了受保护路径）
    return node.editAble === 0 || node.editAble === 1;
  };

  // 检查模块层级
  const getMenuLevel = (node: MenuNode): number => {
    const findLevel = (
      nodes: MenuNode[],
      targetKey: string,
      currentLevel: number = 1
    ): number => {
      for (const item of nodes) {
        if (item.key === targetKey) {
          return currentLevel;
        }
        if (item.children) {
          const level = findLevel(item.children, targetKey, currentLevel + 1);
          if (level > 0) {
            return level;
          }
        }
      }
      return 0;
    };

    return findLevel(treeData, node.key);
  };

  // 添加一级菜单
  const handleAddRootMenu = () => {
    setModalType("addRoot");
    setSelectedNode(null);
    setNewMenuName("");
    setIsModalVisible(true);
  };

  // 添加子菜单
  const handleAdd = (node: MenuNode) => {
    if (!canAddChild(node)) {
      if (node.path === "/home") {
        message.error("首页不允许添加子菜单");
        return;
      }

      const protectedPaths = ["/menuManager", "/userManager"];
      if (protectedPaths.includes(node.path)) {
        message.error("该系统菜单不允许添加子菜单");
        return;
      }

      const menuLevel = getMenuLevel(node);
      if (menuLevel >= 4) {
        message.error("最多只能添加四级菜单");
        return;
      }
    }

    setModalType("add");
    setSelectedNode(node);
    setNewMenuName("");
    setIsModalVisible(true);
  };

  // 处理编辑菜单
  const handleEdit = (node: MenuNode) => {
    if (!canEdit(node)) {
      if (node.editAble === 1) {
        message.error("该菜单为只读菜单，不允许编辑");
      } else {
        message.error("该菜单不允许编辑");
      }
      return;
    }
    setModalType("edit");
    setSelectedNode(node);
    setNewMenuName(node.title);
    setIsModalVisible(true);
  };

  // 修改 handleModalOk
  const handleModalOk = async () => {
    if (!newMenuName.trim()) {
      message.error("请输入菜单名称");
      return;
    }

    setLoading(true);

    try {
      let requestData: {
        id?: number;
        menuName: string;
        parentId: number;
        url: string;
      } = {
        menuName: newMenuName,
        parentId: 0,
        url: "",
      };

      if (modalType === "edit" && selectedNode) {
        // 编辑菜单
        requestData = {
          id: selectedNode.id,
          menuName: newMenuName,
          parentId: selectedNode.id || 0, // 修复类型错误
          url: selectedNode.path,
        };

        const result = await http.post("/api/menu/update", requestData);

        if (+result.status === 200) {
          message.success("编辑菜单成功");
          await refreshMenuData();
          setIsModalVisible(false);
          setNewMenuName("");
          setSelectedNode(null);
        } else {
          message.error(result.message || "编辑菜单失败");
        }
      } else if (modalType === "add" && selectedNode) {
        // 添加子菜单
        requestData = {
          menuName: newMenuName,
          parentId: selectedNode.id || 0, // 修复类型错误
          url: `${selectedNode.path}/${newMenuName.toLowerCase().replace(/\s+/g, "-")}`,
        };

        const result = await http.post("/api/menu/save", requestData);

        if (+result.status === 200) {
          message.success("添加子菜单成功");
          await refreshMenuData();
          setIsModalVisible(false);
          setNewMenuName("");
          setSelectedNode(null);
        } else {
          message.error(result.message || "添加子菜单失败");
        }
      } else if (modalType === "addRoot") {
        // 添加一级菜单
        requestData = {
          id: 0,
          menuName: newMenuName,
          parentId: 0,
          url: `/${newMenuName.toLowerCase().replace(/\s+/g, "-")}`,
        };

        const result = await http.post("/api/menu/save", requestData);

        if (+result.status === 200) {
          message.success("添加一级菜单成功");
          await refreshMenuData();
          setIsModalVisible(false);
          setNewMenuName("");
          setSelectedNode(null);
        } else {
          message.error(result.message || "添加一级菜单失败");
        }
      }
    } catch (error) {
      console.error("菜单操作失败:", error);
      message.error("菜单操作失败");
    } finally {
      setLoading(false);
    }
  };

  // 自定义渲染树节点
  const renderTreeNode = (node: MenuNode) => {
    const canEditNode = canEdit(node);
    const canDeleteNode = canDelete(node);
    const canAddChildNode = canAddChild(node);
    const menuLevel = getMenuLevel(node);

    // 根据 editAble 和特殊路径显示不同的标签
    const getStatusLabel = (node: MenuNode) => {
      // 首页特殊标识
      const protectedPaths = [
        "/home",
        "/menuManager",
        "/userManager",
        "/roleManager",
      ];
      if (protectedPaths.includes(node.path)) {
        return (
          <span
            style={{
              fontSize: "12px",
              color: "#722ed1",
              backgroundColor: "#f9f0ff",
              padding: "2px 6px",
              borderRadius: "4px",
              border: "1px solid #d3adf7",
            }}
          >
            系统
          </span>
        );
      }

      // editAble 状态标识
      if (node.editAble === 1) {
        return (
          <span
            style={{
              fontSize: "12px",
              color: "#faad14",
              backgroundColor: "#fff7e6",
              padding: "2px 6px",
              borderRadius: "4px",
              border: "1px solid #ffd591",
            }}
          >
            只读
          </span>
        );
      }
      if (node.editAble === 0) {
        return (
          <span
            style={{
              fontSize: "12px",
              color: "#52c41a",
              backgroundColor: "#f6ffed",
              padding: "2px 6px",
              borderRadius: "4px",
              border: "1px solid #b7eb8f",
            }}
          >
            可编辑
          </span>
        );
      }
      return null;
    };

    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          width: "100%",
          padding: "4px 8px",
          borderRadius: "6px",
          transition: "all 0.2s",
        }}
        className="menu-tree-node"
      >
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          <MenuOutlined style={{ color: "#1890ff", fontSize: "14px" }} />
          <span
            style={{
              fontWeight: menuLevel === 1 ? "600" : "normal",
              color: menuLevel === 1 ? "#262626" : "#595959",
              fontSize: menuLevel === 1 ? "14px" : "13px",
            }}
          >
            {node.title}
          </span>
          <span
            style={{
              fontSize: "12px",
              color: "#8c8c8c",
              backgroundColor: "#f5f5f5",
              padding: "2px 6px",
              borderRadius: "4px",
            }}
          >
            {menuLevel}级
          </span>
          {getStatusLabel(node)}
        </div>

        <Space size="small">
          {/* 编辑按钮 */}
          {canEditNode && (
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              style={{ color: "#1890ff" }}
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(node);
              }}
              title="编辑菜单"
            />
          )}

          {/* 添加子菜单按钮 - 首页不显示 */}
          {canAddChildNode && (
            <Button
              type="text"
              size="small"
              icon={<PlusOutlined />}
              style={{ color: "#52c41a" }}
              onClick={(e) => {
                e.stopPropagation();
                handleAdd(node);
              }}
              title="添加子菜单"
            />
          )}

          {/* 删除按钮 - 首页不显示 */}
          {canDeleteNode && (
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                console.log("点击删除按钮，节点:", node.title); // 调试日志
                setDeleteTargetNode(node);
                setIsDeleteModalVisible(true);
              }}
              title="删除菜单"
            />
          )}
        </Space>
      </div>
    );
  };

  // 修改 handleDeleteConfirm 函数
  const handleDeleteConfirm = async () => {
    if (!deleteTargetNode) return;

    try {
      setLoading(true);

      const deleteData = {
        id: deleteTargetNode.id,
        menuName: deleteTargetNode.title,
        component: deleteTargetNode.component || "",
        parentId: getParentId(deleteTargetNode),
      };

      const result = await http.post("/api/menu/del", deleteData);

      if (+result.status === 200) {
        const hasChildren =
          deleteTargetNode.children && deleteTargetNode.children.length > 0;
        const childrenCount = countAllChildren(deleteTargetNode);

        if (hasChildren) {
          message.success(
            `删除菜单"${deleteTargetNode.title}"及其${childrenCount}个子菜单成功`
          );
        } else {
          message.success(`删除菜单"${deleteTargetNode.title}"成功`);
        }
        await refreshMenuData();
      } else {
        message.error(result.message || "删除菜单失败");
      }
    } catch (error) {
      console.error("删除菜单失败:", error);
      message.error("删除菜单失败");
    } finally {
      setLoading(false);
      setIsDeleteModalVisible(false);
      setDeleteTargetNode(null);
    }
  };

  // 获取父级ID的函数
  const getParentId = (node: MenuNode): number => {
    // 判断是否为一级菜单
    const menuLevel = getMenuLevel(node);
    if (menuLevel === 1) {
      return 0; // 一级菜单，parentId 为 0
    }

    // 递归查找父级节点ID
    const findParentId = (nodes: MenuNode[], targetKey: string): number => {
      for (const item of nodes) {
        if (item.children) {
          // 检查当前节点的子节点中是否有目标节点
          const found = item.children.find((child) => child.key === targetKey);
          if (found) {
            return item.id || 0;
          }
          // 递归查找更深层的子节点
          const parentId = findParentId(item.children, targetKey);
          if (parentId > 0) {
            return parentId;
          }
        }
      }
      return 0;
    };

    return findParentId(treeData, node.key);
  };

  // 处理删除取消
  const handleDeleteCancel = () => {
    setIsDeleteModalVisible(false);
    setDeleteTargetNode(null);
  };

  // 统计子菜单数量（包括所有层级）
  const countAllChildren = (menuNode: MenuNode): number => {
    if (!menuNode.children || menuNode.children.length === 0) {
      return 0;
    }

    let count = menuNode.children.length;
    menuNode.children.forEach((child) => {
      count += countAllChildren(child);
    });

    return count;
  };

  // 构建删除确认内容
  const getDeleteConfirmContent = () => {
    if (!deleteTargetNode) return "";

    const hasChildren =
      deleteTargetNode.children && deleteTargetNode.children.length > 0;
    const childrenCount = countAllChildren(deleteTargetNode);

    if (hasChildren) {
      return `确定要删除菜单"${deleteTargetNode.title}"吗？\n\n⚠️ 警告：删除此菜单将同时删除 ${childrenCount} 个子菜单！`;
    } else {
      return `确定要删除菜单"${deleteTargetNode.title}"吗？`;
    }
  };

  const getModalTitle = () => {
    switch (modalType) {
      case "addRoot":
        return "添加一级菜单";
      case "add":
        return "添加子菜单";
      case "edit":
        return "编辑菜单";
      default:
        return "菜单操作";
    }
  };

  return (
    <div
      style={{
        padding: "24px",
        backgroundColor: "#f5f5f5",
        minHeight: "100vh",
      }}
    >
      <Card
        title={
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <MenuOutlined style={{ color: "#1890ff" }} />
            <span>模块设置</span>
          </div>
        }
        extra={
          <Space>
            <Button
              icon={<MenuOutlined />}
              onClick={loadMenuData}
              loading={loading}
            >
              刷新数据
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddRootMenu}
              style={{
                borderRadius: "6px",
                boxShadow: "0 2px 4px rgba(24, 144, 255, 0.2)",
              }}
            >
              添加一级菜单
            </Button>
          </Space>
        }
        style={{
          borderRadius: "8px",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
        }}
        loading={loading}
      >
        <div
          style={{
            backgroundColor: "#fafafa",
            padding: "16px",
            borderRadius: "6px",
            border: "1px solid #f0f0f0",
          }}
        >
          <Tree
            treeData={treeData}
            titleRender={renderTreeNode}
            defaultExpandAll
            showLine={{ showLeafIcon: false }}
            style={{
              backgroundColor: "transparent",
            }}
          />
          {treeData.length === 0 && (
            <div
              style={{
                textAlign: "center",
                padding: "40px",
                color: "#8c8c8c",
              }}
            >
              <MenuOutlined
                style={{ fontSize: "48px", marginBottom: "16px" }}
              />
              <div>暂无菜单数据</div>
              <div style={{ fontSize: "12px", marginTop: "8px" }}>
                点击上方"添加一级菜单"按钮开始创建菜单
              </div>
            </div>
          )}
        </div>

        <Divider />

        <div
          style={{
            fontSize: "12px",
            color: "#8c8c8c",
            backgroundColor: "#f9f9f9",
            padding: "12px",
            borderRadius: "4px",
            border: "1px solid #f0f0f0",
          }}
        >
          <div style={{ marginBottom: "4px" }}>
            <strong>操作说明：</strong>
          </div>
          <div>• 支持最多4级菜单结构</div>
          <div>
            • <span style={{ color: "#13c2c2" }}>系统</span>{" "}
            菜单：不可编辑、删除或添加子菜单
          </div>
          <div>
            • <span style={{ color: "#52c41a" }}>可编辑</span>{" "}
            菜单：支持编辑、删除、添加子菜单
          </div>
          <div>
            • <span style={{ color: "#faad14" }}>只读</span>{" "}
            菜单：仅支持添加子菜单，不可编辑或删除
          </div>
          <div>• 菜单修改后会自动同步到侧边栏</div>
        </div>
      </Card>

      <Modal
        title={getModalTitle()}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          setNewMenuName("");
          setSelectedNode(null);
        }}
        confirmLoading={loading}
        width={480}
        style={{ borderRadius: "8px" }}
      >
        <div style={{ padding: "16px 0" }}>
          <div style={{ marginBottom: "12px", color: "#595959" }}>
            {modalType === "addRoot" && "请输入一级菜单名称"}
            {modalType === "add" &&
              selectedNode &&
              `在"${selectedNode.title}"下添加子菜单`}
            {modalType === "edit" &&
              selectedNode &&
              `编辑菜单"${selectedNode.title}"`}
          </div>
          <Input
            placeholder="请输入菜单名称"
            value={newMenuName}
            onChange={(e) => setNewMenuName(e.target.value)}
            onPressEnter={handleModalOk}
            style={{ borderRadius: "6px" }}
            size="large"
          />
        </div>
      </Modal>

      {/* 删除确认Modal */}
      <CustomConfirmModal
        visible={isDeleteModalVisible}
        title="确认删除"
        content={getDeleteConfirmContent()}
        onOk={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        okText="确定删除"
        cancelText="取消"
        okType="danger"
      />
    </div>
  );
};

export default MenuManager;
